<?php

namespace App\Api\Controllers;

use App\Api\Requests\CouponRequest;
use App\Api\TransFormers\AlycouponTransformer;
use App\Api\TransFormers\CommentsTransformer;
use App\Api\TransFormers\CouponinfoTransformer;
use App\Api\TransFormers\CouponTransformer;
use App\Api\TransFormers\MycouponTransformer;
use App\Models\Comment;
use App\Models\CommentsLike;
use App\Models\Browse;
use App\Models\Coupon;
use App\Models\Keyword;
use App\Models\Mycoupon;
use App\Models\Order;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Pagination\LengthAwarePaginator;

class CouponController extends BaseController
{

    /**
     * 获取优惠券详情
     */
    public function info(CouponRequest $request)
    {
        $id = $request->get('id');
        $info = Coupon::where([
            ['id', $id]
        ])->first();

        return $this->response->item($info, new CouponinfoTransformer());
    }

    /**
     * 获取优惠券的评论
     */
    public function comments(CouponRequest $request)
    {
        $id = $request->get('id');
        $list = Comment::with('user')->where([
            ['coupon_id', $id],
            ['status', 2]
        ])->latest('fabulous_num')->latest('created_at')->paginate(10);
        //$list = $list->sortBy('fabulous_num');

        return $this->response->paginator($list, new CommentsTransformer());
    }

    /**
     * 对优惠券进行评论
     */
    public function commenting(CouponRequest $request)
    {
        $openid = $request->get('openid');
        $id = $request->get('id');
        $userInfo = User::where(['openid' => $openid])->first();
        $comments = $request->get('comments');

        $ins = new Comment();
        $ins->user_id = $userInfo['id'];
        $ins->coupon_id = $id;
        $ins->content = $comments;
        $ins->status = 2;

        \DB::beginTransaction();
        try {
            $ins->save();
        } catch (\Exception $error) {
            \DB::rollBack();
            return $this->response->errorInternal();
        }
        \DB::commit();

        return $this->response->created();
    }

    /**
     * 对优惠券的评论点赞
     */
    public function commentsLike(CouponRequest $request)
    {
        $userInfo = User::where(['openid' => $request->get('openid')])->first();
        $comment_id = $request->get('comment_id');
        $like = CommentsLike::where([
            ['comment_id', $comment_id],
            ['user_id', $userInfo['id']]
        ])->first();

        if (empty($like->id)) {
            $ins = new CommentsLike();
            $ins->comment_id = $comment_id;
            $ins->user_id = $userInfo['id'];

            \DB::beginTransaction();
            try {
                $ins->save();
            } catch (\Exception $error) {
                \DB::rollBack();
                return $this->response->errorInternal();
            }

            // 对评论的点赞数加一
            $comments = Comment::where(['id' => $comment_id])->first();
            $comments->fabulous_num = $comments->fabulous_num + 1;
            try {
                $comments->save();
            } catch (\Exception $error) {
                \DB::rollBack();
                return $this->response->errorInternal();
            }

            \DB::commit();
        }
        return $this->response->created();
    }

    /**
     * 获取附近优惠券
     */
    public function lists(CouponRequest $request)
    {
        $lng = $request->get('lng');
        $lat = $request->get('lat');
        $type = $request->get('type', 0); // 优惠券分类
        $pageNow = $request->get('page', 1);
        $pageSize = 20;
        $date = date('Y-m-d', time());
        $where = [
            ['status', 1], // 0:下架,1:显示
            ['count', '>', 0], // 库存大于1
            ['verify', 2], // 审核通过
            ['end', '>=', $date]
        ];
        if($type > 1){
            array_push($where,['type', $type]);
        }
        $list = app(Coupon::class)->getNearLists($lng, $lat, $where);

        $list = new LengthAwarePaginator($list->forPage($pageNow, $pageSize), $list->count(), $pageSize);
        return $this->response->paginator($list, new CouponTransformer());
    }

    /*
     * 我的优惠券
     * */
    public function mycoupon(CouponRequest $request)
    {
        $date = date('Y-m-d', time());
        $type = $request->get('status'); // 1:未使用;2:已使用;3:已过期
        $userInfo = User::where('openid', $request->get('openid'))->first();

        $where = [
            ['user_id', $userInfo['id']],
            ['status', 2] // 已支付
        ];
        if ($type == 1) {
            array_push($where, ['type', 1]); // 未使用
            $list = Order::with('coupon')->whereHas('coupon', function ($query) use ($date) {
                $where = [
                    ['end', '>=', $date]
                ];
                $query->where($where);
            })->where($where)->latest('created_at')->paginate(10);
        }
        if ($type == 2) {
            array_push($where, ['type', 2]);
            $list = Order::where($where)->latest('created_at')->paginate(10);
        }
        if ($type == 3) {
            array_push($where, ['type', 1]);
            $list = Order::whereHas('coupon', function ($query) use ($date) {
                $where = [
                    ['end', '<', $date]
                ];
                $query->where($where);
            })->where($where)->latest('created_at')->paginate(10);
        }
        //dd($list->toarray());
        return $this->response->paginator($list, new MycouponTransformer());
    }

    /**
     * 返回我的优惠券三种状态的个数
     */
    public function mycoupon_allnum(CouponRequest $request)
    {
        $date = date('Y-m-d', time());
        $userInfo = User::where('openid', $request->get('openid'))->first();

        $wheres = [
            ['user_id', $userInfo['id']],
            ['status', 2] // 已支付
        ];
        $where1 = array_merge($wheres, [['type', 1]]); // 未使用
        $num1 = Order::whereHas('coupon', function ($query) use ($date) {
            $where = [
                ['end', '>=', $date]
            ];
            $query->where($where);
        })->where($where1)->count();

        $where2 = array_merge($wheres, [['type', 2]]);
        $num2 = Order::where($where2)->count();

        $where3 = array_merge($wheres, [['type', 1]]);
        $num3 = Order::whereHas('coupon', function ($query) use ($date) {
            $where = [
                ['end', '<', $date]
            ];
            $query->where($where);
        })->where($where3)->count();
        $arr = [
            'unused' => $num1,
            'used' => $num2,
            'overtime' => $num3
        ];
        return $arr;
    }

    /**
     * 获取我已经发布的优惠券
     */
    public function alycoupons(CouponRequest $request)
    {
        $userInfo = User::where(['openid' => $request->get('openid')])->first();
        $list = Coupon::where([
            ['user_id', $userInfo['id']]
        ])->latest('created_at')->paginate(10);
        return $this->response->paginator($list, new AlycouponTransformer());
    }

    /**
     * 上架和下架我发布的优惠券
     */
    public function upOrdown(CouponRequest $request)
    {
        $userInfo = User::where(['openid' => $request->get('openid')])->first();
        $id = $request->get('id');
        $info = Coupon::where([
            ['id', $id],
            ['user_id', $userInfo['id']]
        ])->first();
        if (!$info) {
            return $this->response->errorInternal();
        }

        if ($info->status == 1) {
            $info->status = 0;
        } else {
            $info->status = 1;
        }

        \DB::beginTransaction();
        try {
            $info->save();
        } catch (\Exception $error) {
            \DB::rollBack();
            return $this->response->errorInternal();
        }
        \DB::commit();
        // 操作后优惠券的信息
        $coupon = Coupon::where([
            ['id', $id],
            ['user_id', $userInfo['id']]
        ])->first();

        return ['status' => $coupon->status];
    }

    /**
     * 添加优惠券
     * @param SearchRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function publish(CouponRequest $request)
    {
        if($request->get('prefer_value') > 999.99 || $request->get('prefer_value') < 0){
            return $this->response->error('优惠值超出范围',400);
        }
        $keyword = $request->get('keyword');
        $keyword = str_replace('，', ',', $keyword);
        $keyword = str_replace('、', ',', $keyword);
        $userInfo = User::where('openid', $request->get('openid'))->first();
        $ins = new Coupon();
        $ins->user_id = $userInfo->id;
        $ins->name = $request->get('name') . $request->get('prefer_value') . $ins->preferText[$request->get('prefer_type')] . '优惠券';
        $ins->type = $request->get('type');
        $ins->limit = $request->get('limit');
        $ins->prefer_type = $request->get('prefer_type');
        $ins->prefer_value = $request->get('prefer_value');
        $ins->count = $request->get('num');
        $ins->phone = $request->get('phone');
        $ins->week = app(Coupon::class)->weekKey[$request->get('week')];
        $ins->address = $request->get('address');
        $ins->time = app(Coupon::class)->timeKey[$request->get('time')];
        $ins->start = $request->get('start');
        $ins->end = $request->get('end');
        $ins->status = 1;
        $ins->longitude = $request->get('lng');
        $ins->latitude = $request->get('lat');
        $ins->img = $request->get('img');
        $ins->content = $keyword;

        $ins->save();

        \DB::beginTransaction();
        try {
            $ins->save();
        } catch (\Exception $error) {
            \DB::rollBack();
            return $this->response->errorInternal();
        }

        \DB::commit();
        return $this->response->created();
    }

    public function browse(CouponRequest $request)
    {
        $openid = $request->get('openid');
        $info = User::where('openid', $openid)->first();
        $userid = $info->id;
        $couponid = $request->get('couponid');
        $where = [
            ['user_id', $userid],
            ['coupon_id', $couponid]
        ];
        $res = Browse::where($where)->first();
        if ($res) {
            $browse = Coupon::find($couponid);
            $browse->browse = $browse->browse + 1;
            $browse->save();
            return $this->response->created();
        }
        $time = Carbon::now();
        $data = ['user_id' => $userid, 'coupon_id' => $couponid, 'browsed_at' => $time];
        $browse = Coupon::find($couponid);
        $browse->browse = $browse->browse + 1;
        $browse->save();
        Browse::insert($data);
        return $this->response->created();
    }
}